<template>
  <div class="customer-detail-box">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>客户信息&nbsp;ID：{{ form.id }}</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入客户姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6"> 
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职业" prop="occupation">
              <el-select v-model="form.occupation" placeholder="请选择职业" clearable>
                <el-option
                  v-for="dict in occupationOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学历" prop="education">
              <el-select v-model="form.education" placeholder="请选择学历" clearable>
                <el-option
                  v-for="dict in educationOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所在地区">
              <el-cascader
                v-model="area"
                size="large"
                :options="provinceAndCityData"
                @change="handleChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="微信号" prop="weixin">
              <el-input v-model="form.weixin" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="form.age" :precision="0" :min="1" :max="99" :step="1" placeholder="请输入年龄" controls-position="right" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="专业" prop="major">
              <el-select v-model="form.major" placeholder="请选择专业" clearable>
                <el-option
                  v-for="dict in majorOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="在职情况" prop="job">
              <el-select v-model="form.job" placeholder="请选择在职情况" clearable>
                <el-option
                  v-for="dict in jobOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="当前薪资" prop="salary">
              <el-select v-model="form.salary" placeholder="请选择当前薪资" clearable>
                <el-option
                  v-for="dict in salaryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="qq" prop="qq">
              <el-input v-model="form.qq" placeholder="请输入qq" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别" prop="sex">
              <el-radio-group v-model="form.sex">
                <el-radio
                  v-for="dict in sexOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue">
                  {{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="目标薪资" prop="expectedSalary">
              <el-select v-model="form.expectedSalary" placeholder="请选择目标薪资" clearable>
                <el-option
                  v-for="dict in salaryOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="wp-50" label="备注" prop="remark">
              <el-input v-model="form.remark" type="text" :rows="1" show-word-limit placeholder="请输入备注" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>客户意向</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="意向学科" prop="subject">
              <el-select v-model="form.subject" placeholder="请选择意向学科" clearable @change="subjectChangeHandle">
                <el-option
                  v-for="dict in subjectOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="学习原因" prop="reasons">
              <el-input v-model="form.reasons" placeholder="请输入学习原因" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="职业计划" prop="plan">
              <el-input v-model="form.plan" placeholder="请输入职业计划" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间计划" prop="planTime">
              <el-date-picker
                v-model="form.planTime"
                clearable
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择时间计划"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="意向课程" prop="courseId">
              <el-select v-model="form.courseId" placeholder="请选择意向课程" clearable @change="courseHandle">
                <el-option
                  v-for="dict in courseOptions"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="意向金额">
              <el-input v-model="interestAmount" disabled placeholder="请输入意向金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他意向" prop="otherIntention">
              <el-input v-model="form.otherIntention" type="text" :rows="1" show-word-limit placeholder="请输入其他意向" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card class="box-card" style="margin-bottom:10px">
        <div slot="header" class="clearfix">
          <span>添加沟通记录</span>
        </div>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="跟进状态" prop="trackStatus">
              <el-select v-model="form.trackStatus" placeholder="请选择跟进状态" clearable>
                <el-option
                  v-for="dict in trackStatusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下次跟进时间" prop="nextTime" label-width="110px">
              <el-date-picker
                v-model="form.nextTime"
                clearable
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                format="yyyy-MM-dd HH:mm"
                placeholder="请选择下次跟进时间"
                default-time="12:00:00"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="沟通重点" prop="keyItemsArray">
              <el-select v-model="form.keyItemsArray" multiple placeholder="请选择沟通重点" clearable>
                <el-option
                  v-for="dict in keyItemsOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="沟通纪要" prop="record">
              <el-input v-model="form.record" type="text" show-word-limit placeholder="请输入沟通纪要" maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-button style="float: right;" type="danger" @click="handleReport()">踢回公海</el-button>
            <el-button style="float: right;margin-right:10px" type="success" @click="handleContract()">转交成客户</el-button>
            <el-button style="float: right;" type="primary" @click="doSave()">保存</el-button>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>历史跟进记录</span>
      </div>
      <el-table :data="pageData.data" style="width: 100%" border>
        <el-table-column prop="createTime" label="本次沟通时间"></el-table-column>
        <el-table-column prop="keyItems" label="沟通重点">
          <template slot-scope="scope">
            <div v-if="scope.row.keyItems">
              <span v-for="item in (scope.row.keyItems.split(','))" :key="item">
                {{ keyItemsFormat(item) }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="record" label="沟通状态">
          <template slot-scope="scope">
            {{ trackStatusFormat(scope.row.trackStatus) }}
          </template>
        </el-table-column>
        <el-table-column prop="nextTime" label="下次跟进时间"></el-table-column>
        <el-table-column prop="record" label="沟通纪要"></el-table-column>
        <el-table-column prop="createBy" label="沟通人"></el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageData.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="pageData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.totalCount">
      </el-pagination>
    </el-card>

    <el-dialog title="踢回公海" :visible.sync="dialogReportVisible">
      <el-form ref="reportForm" :model="reportForm" :rules="reportRules" label-width="90px">
        <el-form-item class="wp-100" label="原因" prop="backReason">
          <el-select v-model="reportForm.backReason" placeholder="请选择原因">
            <el-option
              v-for="dict in backReasonOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogReportVisible = false">取 消</el-button>
        <el-button type="primary" @click="doReportSave">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="转换客户" :visible.sync="dialogContractVisible">
      <el-form ref="contractForm" :model="contractForm" :rules="contractRules" label-width="110px">
        <el-form-item label="客户手机号" prop="phone">
          <el-input v-model="contractForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="contractForm.contractNo" placeholder="请输入合同编号" maxlength="20" />
        </el-form-item>
        <el-form-item label="上传合同" prop="fileName">
          <el-upload
            ref="upload"
            action="/api/file/upload"
            :limit="1"
            :before-upload="beforeFileUpload"
            :on-success="handleFileSuccess"
            :headers="{'Authorization': 'Bearer '+ $store.state.token}"
            :show-file-list="true">
            <!-- 上传按钮 -->
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogContractVisible = false">取 消</el-button>
        <el-button type="primary" @click="doContractSave">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { provinceAndCityData, CodeToText, TextToCode } from 'element-china-area-data'
export default {
  data () {
    /* 验证QQ */
    const isValidateQq=(rule, value, callback)=> {
      if(value){
        let reg = /^[1-9][0-9]{4,9}$/gim;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的QQ号'))
        } else {
          callback()
        }
      }else{
        callback()
      }
      return true
    };
    /* 验证微信 */
    const isValidateWx =(rule, value, callback)=> {
      if(value){
        let reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/;
        if (!reg.test(value)) {
          callback(new Error('请输入正确的微信号'))
        } else {
          callback()
        }
      }else{
        callback()
      }
      return true
    };
    return {
      //查询的数据模型
      searchForm: {
        //过滤条件
        businessId: null,
        //分页条件
        pageNo: 1,
        pageSize: 5,
      },
      // 详情数据
      form: {

      },
      //意向金额
      interestAmount: 0,
      //新增跟进记录对话框显示标记
      dialogSaveRecordVisible:false,
      //伪线索上报对话框显示标记
      dialogReportVisible:false,
      //合同
      dialogContractVisible:false,
      occupationOptions: [],
      educationOptions: [],
      majorOptions: [],
      jobOptions: [],
      salaryOptions: [],
      // 性能字典
      sexOptions: [],
      // 意向学科字典
      subjectOptions: [],
      // 状态字典
      statusOptions: [],
      channelOptions: [],
      courseOptions: [],
      trackStatusOptions: [],
      keyItemsOptions: [],
      backReasonOptions: [],
      provinceAndCityData:provinceAndCityData,
      area:[],
      //跟进记录
      pageData: {
        data: [], // 分页数据
        pageNo: 1, // 当前页
        pageSize: 5, // 一页的大小
        totalCount: 0, // 总数据量
        totalPageCount: 0, // 总页数
      },
      //新增跟进记录的表单验证规则
      rules:{
        name: [
          { required: true, message: '客户姓名不能为空', trigger: 'blur' },
        ],
        level: [
          { required: true, message: '意向等级不能为空', trigger: 'change' }
        ],
        subject: [
          { required: true, message: '意向学科不能为空', trigger: 'change' }
        ],
        record: [
          { required: true, message: '跟进记录不能为空', trigger: 'blur' }
        ],
        nextTime: [
          { required: true, message: '下次跟进时间不能为空', trigger: 'blur' }
        ],
        weixin: [
          { validator: isValidateWx, message: '请输入正确的微信号' }
        ],
        qq: [
          { validator: isValidateQq, message: '请输入正确的QQ号' }
        ]
      },
      // 踢回公海表单参数
      reportForm: {
        businessId: null,
        backReason: null
      },
      // 踢回公海表单验证规则
      reportRules:{
         backReason: [
          { required: true, message: '原因不能为空', trigger: 'blur' }
        ]
      },
      contractForm: {
        businessId: null,
        phone: null,
        contractNo: null,
        fileName: null
      },
      contractRules:{
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
        ],
        contractNo: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' }
        ],
        fileName: [
          { required: true, message: '请上传pdf格式的合同', trigger: 'change' }
        ]
      }
    }
  },
  created () {
    this.searchForm.businessId = this.$route.query.id
    //查询页面所需的数据字典
    this.getDicList()
    //查询线索信息
    this.getInfo()
    //查询跟进记录
    this.getRecordList()
  },
  methods: {
    //查询线索详情
    getInfo () {
      this.$axios.get("/api/tb/business/view/"+this.searchForm.businessId)
        .then((res) => {
          if (res.data.code == 200) {
            this.form = res.data.data

            if (this.form.provinces && this.form.city) {
              this.area = [TextToCode[this.form.provinces].code, TextToCode[this.form.provinces][this.form.city].code]
            }
            if (this.form.subject) {
              this.getCourseList()
            }
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
    //查询线索跟进记录
    getRecordList () {
      this.$axios.get("/api/tb/businessRecord/list", {params:this.searchForm})
        .then((res) => {
          if (res.data.code == 200) {
            this.pageData.pageNo = res.data.data.current;
            this.pageData.pageSize = res.data.data.size;
            this.pageData.totalCount = res.data.data.total;
            this.pageData.totalPageCount = res.data.data.pages;
            this.pageData.data = res.data.data.records;
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    //改变每页显示的条数
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.getRecordList();
    },
    //改变当前的页码数
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.getRecordList();
    },
    // 回显数据字典
    selectDictLabel(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].dictValue == ('' + value)) {
          actions.push(datas[key].dictLabel);
          return true;
        }
      })
      return actions.join('');
    },
    keyItemsFormat (val) {
      return this.selectDictLabel(this.keyItemsOptions, val)
    },
    trackStatusFormat (val) {
      return this.selectDictLabel(this.trackStatusOptions, val)
    },
    getDicts(dictType){
      return new Promise((resolve, reject) => {
        this.$axios.get("/api/sys/dictData/optionselect/"+dictType)
          .then((res) => {
            if (res.data.code == 200) {
              resolve(res.data);
            } else {
              this.$message.error(res.data.msg);
            }
          })
      })
    },
    //查询数据字典
    getDicList () {
       this.getDicts('reasons_for_business_reporting').then(response => {
        this.backReasonOptions = response.data
      })
       this.getDicts('sys_user_sex').then(response => {
        this.sexOptions = response.data
      })
      this.getDicts('course_subject').then(response => {
        this.subjectOptions = response.data
      })
      this.getDicts('clue_status').then(response => {
        this.statusOptions = response.data
      })
      this.getDicts('clues_item').then(response => {
        this.channelOptions = response.data
      })
      this.getDicts('communication_point').then(response => {
        this.keyItemsOptions = response.data
      })
      this.getDicts('occupation').then(response => {
        this.occupationOptions = response.data
      })
      this.getDicts('education').then(response => {
        this.educationOptions = response.data
      })
      this.getDicts('major').then(response => {
        this.majorOptions = response.data
      })
      this.getDicts('job').then(response => {
        this.jobOptions = response.data
      })
      this.getDicts('salary').then(response => {
        this.salaryOptions = response.data
      })
      this.getDicts('track_status').then(response => {
        this.trackStatusOptions = response.data
      })
    },
    clearText () {
      this.$nextTick(() => {
        this.$refs.form.clearValidate('trackStatus')
        this.$refs.form.clearValidate('nextTime')
        this.$refs.form.clearValidate('keyItems')
        this.$refs.form.clearValidate('keyItemsArray')
        this.$refs.form.clearValidate('record')
      })
      this.form.trackStatus = null
      this.form.nextTime = null
      this.form.keyItems = null
      this.form.keyItemsArray = []
      this.form.record = null
    },
    //保存
    doSave() {
      this.form.businessId=this.searchForm.businessId;
      this.form.keyItems = this.form.keyItemsArray.toString();
      this.$refs["form"].validate((vali) => {
        if (vali) {
          //发送ajax请求
          this.$axios.post("/api/tb/businessRecord/save", this.form)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogSaveRecordVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.getRecordList();
                // 4.清空添加沟通记录表单
                this.clearText()
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
        }
      });
    },
    // 踢回公海
    handleReport () {
      //显示对话框
      this.dialogReportVisible=true;
    },
    //踢回公海
    doReportSave() {
      this.$refs["reportForm"].validate((vali) => {
        if (vali) {
          this.reportForm.businessId = this.form.id;
          //发送ajax请求
          this.$axios.put("/api/tb/business/backBusiness", this.reportForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogReportVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.$router.back();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
        }
      });
    },
    handleContract(){
      //显示对话框
      this.dialogContractVisible=true;
    },
    // 转客户
    doContractSave() {
      this.$refs["contractForm"].validate((vali) => {
        if (vali) {
          this.contractForm.businessId = this.form.id;
          //发送ajax请求
          this.$axios.put("/api/tb/business/changeContract", this.contractForm)
            .then((res) => {
              if (res.data.code == 200) {
                //1.关闭对话框
                this.dialogContractVisible = false;
                //2.友好提示
                this.$message.success(res.data.msg);
                //3.刷新表格
                this.$router.back();
              } else {
                //1.友好提示
                this.$message.error(res.data.msg);
              }
            })
        }
      });
    },
    handleChange (value) {
      console.log(value);
      if (value && value.length > 0) {
        this.form.provinces = CodeToText[value[0]]
        this.form.city = CodeToText[value[1]]
      } else {
        this.form.provinces = ''
        this.form.city = ''
      }
    },
    subjectChangeHandle () {
      this.$nextTick(() => {
        this.$refs.form.clearValidate('courseId')
      })
      this.form.courseId = null
      this.getCourseList()
    },
    getCourseList () {
      this.courseOptions = []
      this.interestAmount = 0
      this.$axios.get("/api/tb/course/optionselect?subject="+this.form.subject)
        .then((res) => {
          if (res.data.code == 200) {
            this.courseOptions = res.data.data;

            if (this.form.courseId !== null && this.form.courseId !== '') {
              this.courseHandle(this.form.courseId)
            }
          } else {
            this.$message.error(res.data.msg);
          }
        })
    },
    courseHandle (id) {
      const course = this.courseOptions.find(item => item.id === id)
      if (course) {
        this.interestAmount = course.price
      } else {
        this.form.courseId = null
        this.interestAmount = 0
      }
    },
    handleFileSuccess(res, file) {
      this.contractForm.fileName = res.data;
    },
    beforeFileUpload(file) {
      const isPDF = file.type === 'application/pdf';
      const isLt2M = file.size / 1024 / 1024 < 10;

      if (!isPDF) {
        this.$message.error('上传文件只能是 pdf 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!');
      }
      return isPDF && isLt2M;
    }
  }
}
</script>
<style scoped>
   .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
</style>
